﻿namespace LiteBlog.Components
{
    using System;
    using System.Web;
    using System.Web.Caching;
    using LiteBlog.Common.Entities;
    using LiteBlog.Components.Enums;
    using LiteBlog.Components.Contracts;


    public class CacheComp : ICacheComp
    {
        private ICacheContext _context;

        public CacheComp(ICacheContext context)
        {
            _context = context;
        }

        public T Get<T>(CacheType type) where T : class
        {
            return Get<T>(type.ToString());
        }

        public Post GetPost(string fileId)
        {
            var cacheKey = GetCacheKey(CacheType.Post, fileId);
            return Get<Post>(cacheKey);
        }

        public Page GetPage(string fileId)
        {
            var cacheKey = GetCacheKey(CacheType.Page, fileId);
            return Get<Page>(cacheKey);
        }       

        public void Put(CacheType type, object value)
        {
            if (HttpContext.Current == null)
                return;

            CacheDependency dep = _context.GetDependency(type);
            Put(type.ToString(), value, dep, TimeSpan.Zero);
        }

        public void PutPost(string fileId, Post post)
        {
            string cacheKey = GetCacheKey(CacheType.Post, fileId);
            CacheDependency dep = _context.GetDependency(CacheType.Post, fileId);
            Put(cacheKey, post, dep, new TimeSpan(0, 5, 0));
        }

        public void PutPage(string fileId, Page page)
        {
            string cacheKey = GetCacheKey(CacheType.Page, fileId);
            CacheDependency dep = _context.GetDependency(CacheType.Page, fileId);
            Put(cacheKey, page, dep, new TimeSpan(0, 30, 0));
        }

        private string GetCacheKey(CacheType cacheType, string fileId)
        {
            // Xac - any string to make the cacheKey unique
            return string.Format("{0}.Xac.{1}", cacheType.ToString(), fileId);
        }

        private void Put(string key, object value, CacheDependency dependency, TimeSpan timeSpan)
        {
            if (HttpContext.Current == null)
                return;

            if (timeSpan == TimeSpan.Zero)
                timeSpan = TimeSpan.FromHours(3.0);

            HttpContext.Current.Cache.Insert(key, value, dependency, Cache.NoAbsoluteExpiration, timeSpan);
        }

        private T Get<T>(string key) where T : class
        {
            if (HttpContext.Current != null)
            {
                return (T)HttpContext.Current.Cache[key];
            }

            return null;
        }
    }
}